<!-- 话题列表 -->
<template id="topicList-template">
  <div>
    <div class="main">
      <div class="navbar">
        <el-button type="primary" plain size="small" v-if="visible == 'false'"
                   @click="$router.push({path: '/admin/control/topic/list', query:{ visible : true}})">返回
        </el-button>
        <el-button type="primary" plain size="small" v-if="visible == 'false'" @click="reductionTopic($event)">还原
        </el-button>
        <el-button type="primary" plain size="small" v-if="visible == 'true'"
                   @click="$router.push({path: '/admin/control/topic/manage/add', query:{ visible : true,page:($route.query.page != undefined ? $route.query.page:'')}})">
          添加话题
        </el-button>
        <el-button type="primary" plain size="small" v-if="visible == 'true'"
                   @click="$router.push({path: '/admin/control/topic/list', query:{ visible : false}})">回收站
        </el-button>
        <el-button type="primary" plain size="small" @click="deleteTopic($event)">批量删除</el-button>
      </div>
      <div class="data-table">
        <el-table ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%"
                  @selection-change="handleSelectionChange" stripe empty-text="没有内容">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="title" label="话题标题" min-width="200">
            <template #default="scope">
              <span>{{ scope.row.title }}</span>
              <span class="essence" v-if="scope.row.essence == true">精华</span>
              <span class="top" v-if="scope.row.sort >0">置顶</span>
              <span v-if="scope.row.giveRedEnvelopeId != null && scope.row.giveRedEnvelopeId != ''" class="redEnvelope">红包</span>
            </template>
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称" align="center" min-width="80"></el-table-column>
          <el-table-column label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag effect="dark" v-if="scope.row.status==10" class="tag-wrapper">待审核</el-tag>
              <el-tag effect="dark" v-if="scope.row.status==20" type="success" class="tag-wrapper">已发布</el-tag>
              <el-tag effect="dark" v-if="scope.row.status==110" type="info" class="tag-wrapper">待审核删除</el-tag>
              <el-tag effect="dark" v-if="scope.row.status==120" type="warning" class="tag-wrapper">已发布删除</el-tag>
            </template>

          </el-table-column>
          <el-table-column label="允许评论" align="center" width="80">
            <template #default="scope">
              <el-tag effect="dark" v-if="scope.row.allow==true" type="success" class="tag-wrapper">允许</el-tag>
              <el-tag effect="dark" v-if="scope.row.allow==false" type="danger" class="tag-wrapper">禁止</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="会员/员工" align="center" min-width="120">
            <template #default="scope">
              <el-popover effect="light" trigger="hover" placement="top">
                <template #default>
                  <p v-if="scope.row.isStaff == false">呢称: {{ scope.row.nickname }}</p>
                  <p>用户名称: {{ scope.row.userName }}</p>
                </template>
                <template #reference v-if="scope.row.isStaff == false">
                  <div class="avatar-wrapper">
                    <div class="avatar-badge" v-if="scope.row.avatarName == null || scope.row.avatarName == ''">
                      <el-avatar :size="48" icon="el-icon-user-solid"></el-avatar>
                    </div>
                    <div class="avatar-badge" v-if="scope.row.avatarName != null && scope.row.avatarName != ''">
                      <el-avatar :size="48" :src="scope.row.avatarPath+'100x100/'+scope.row.avatarName"></el-avatar>
                    </div>

                    <div class="avatar-text">{{ scope.row.userName }}</div>
                  </div>
                </template>

                <template #reference v-if="scope.row.isStaff == true">
                  <div class="avatar-wrapper">
                    <el-badge value="员工" type="warning" class="avatar-badge">
                      <el-avatar :size="48" icon="el-icon-user-solid"></el-avatar>
                    </el-badge>
                    <div class="avatar-text">{{ scope.row.userName }}</div>
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="postTime" label="发布时间" align="center" width="150"></el-table-column>
          <el-table-column prop="sort" label="排序" align="center" width="80"></el-table-column>
          <el-table-column label="操作" align="center" min-width="120">
            <template #default="scope">
              <div class="button-group-wrapper">
                <el-button-group>
                  <el-button type="primary" size="mini"
                             @click="$store.commit('setCacheNumber');$router.push({path: '/admin/control/topic/manage/view', query:{ visible : ($route.query.visible != undefined ? $route.query.visible:''),topicId : scope.row.id}})">
                    查看
                  </el-button>
                  <el-button type="primary" size="mini" @click="deleteTopic($event,scope.row)">删除</el-button>
                </el-button-group>
              </div>
            </template>

          </el-table-column>
        </el-table>
        <div class="pagination-wrapper" v-if="total>0">
          <el-pagination background @current-change="page" :current-page="listQuery.current" :page-size="listQuery.size"
                         layout="total, prev, pager, next,jumper" :total="total"></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//话题列表
export default ({
  name: 'topicList',//组件名称，keep-alive缓存需要本参数
  template: '#topicList-template',
  inject: ['reload'],
  data: function data() {
    return {
      list: [],//表格内容
      visible: 'true',//是否显示 true:未删除话题 false:已删除话题
      multipleSelection: [],

      total: 0,
      listQuery: {
        current: 1,
        size: 10
      }
    };
  },

  created: function created() {
    //设置缓存
    this.$store.commit('setCacheComponents', [this.$route.name]);
    if (this.$route.query.visible != undefined && this.$route.query.visible != '') {
      this.visible = this.$route.query.visible;
    }
    if (this.$route.query.page != undefined && this.$route.query.page != '') {
      this.listQuery.current = this.$route.query.page;
    }
    this.fetchList();
  },
  methods: {
    //查询话题列表
    fetchList: function () {
      let _self = this;
      //清空内容
      _self.list = [];
      this.$ajax.get('control/topic/list', {
        params: {
          visible: _self.visible,
          page: _self.listQuery.current,
          current: _self.listQuery.current,
          size: _self.listQuery.size
        }
      }).then(function (response) {
        console.log(response.data)
        const {code, data, message} = response.data
        if (code === 200) {//成功
          _self.list = data.records;
          _self.total = data.total;
          _self.listQuery.current = data.current;
          _self.listQuery.size = data.size;
        } else if (code === 500) {
          console.log(message)
        }
      }).catch(function (error) {
        console.log(error);
      });
    },
    //分页
    page: function (page) {
      //删除缓存
      this.$store.commit('setCacheNumber');
      this.$router.push({
        path: '/admin/control/topic/list',
        query: {visible: this.visible, page: page}
      });
    },
    //处理多选
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    //删除话题
    deleteTopic: function (event, row) {
      //强制失去焦点
      let target = event.target;
      // 根据button组件内容 里面包括一个span标签，如果设置icon，则还包括一个i标签，其他情况请自行观察。
      // 所以，在我们点击到button组件上的文字也就是span标签上时，直接执行e.target.blur()不会生效，所以要加一层判断。
      if (target.nodeName == 'SPAN' || target.nodeName == 'I') {
        target = event.target.parentNode;
      }
      target.blur();
      let _self = this;
      if (row) {//选中行
        this.$refs.multipleTable.toggleRowSelection(row, true);
      }
      if (this.multipleSelection.length < 1) {
        this.$message.error('至少要选择一行数据');
        return;
      }
      this.$confirm('此操作将删除该话题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let formData = new FormData();
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let rowData = this.multipleSelection[i];
          formData.append('topicId', rowData.id);
        }
        this.$ajax({
          method: 'post',
          url: 'control/topic/manage?method=delete',
          data: formData
        }).then(function (response) {
          if (response == null) {
            return;
          }
          let result = response.data;
          if (result) {

            let returnValue = JSON.parse(result);
            if (returnValue.code === 200) {//成功
              //删除缓存
              _self.$store.commit('setCacheNumber');
              _self.$message.success("删除成功");
              _self.fetchList();
            } else if (returnValue.code === 500) {//错误
              let errorMap = returnValue.data;
              let htmlContent = "";
              let count = 0;
              for (let key in errorMap) {
                count++;
                htmlContent += "<p>" + count + ". " + errorMap[key] + "</p>";
              }
              _self.$alert(htmlContent, '错误', {
                showConfirmButton: false,
                dangerouslyUseHTMLString: true
              }).catch(function (error) {
                console.log(error);
              });
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      }).catch((error) => {
        //取消选中行
        this.$refs.multipleTable.toggleRowSelection(row, false);
        console.log(error);
      });
    },
    //还原话题
    reductionTopic: function (event) {
      //强制失去焦点
      let target = event.target;
      // 根据button组件内容 里面包括一个span标签，如果设置icon，则还包括一个i标签，其他情况请自行观察。
      // 所以，在我们点击到button组件上的文字也就是span标签上时，直接执行e.target.blur()不会生效，所以要加一层判断。
      if (target.nodeName == 'SPAN' || target.nodeName == 'I') {
        target = event.target.parentNode;
      }
      target.blur();
      let _self = this;
      if (this.multipleSelection.length < 1) {
        this.$message.error('至少要选择一行数据');
        return;
      }
      this.$confirm('此操作将还原该话题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let formData = new FormData();
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let rowData = this.multipleSelection[i];
          formData.append('topicId', rowData.id);
        }
        this.$ajax({
          method: 'post',
          url: 'control/topic/manage?method=reduction',
          data: formData
        }).then(function (response) {
          if (response == null) {
            return;
          }
          let result = response.data;
          if (result) {

            let returnValue = JSON.parse(result);
            if (returnValue.code === 200) {//成功
              //删除缓存
              _self.$store.commit('setCacheNumber');
              _self.$message.success("还原成功");
              _self.fetchList();
            } else if (returnValue.code === 500) {//错误

              let errorMap = returnValue.data;
              let htmlContent = "";
              let count = 0;
              for (let key in errorMap) {
                count++;
                htmlContent += "<p>" + count + ". " + errorMap[key] + "</p>";
              }
              _self.$alert(htmlContent, '错误', {
                showConfirmButton: false,
                dangerouslyUseHTMLString: true
              }).catch(function (error) {
                console.log(error);
              });
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      }).catch((error) => {
        console.log(error);
      });
    }
  }
});


</script>